package org.happycomp.radio.planner.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.happycomp.radio.Station;
import org.happycomp.radio.StopDownloadCondition;
import org.happycomp.radio.planner.PlannedItem;
import org.happycomp.radio.planner.Planner;
import org.happycomp.radio.scheduler.Scheduler;

public class PlannerImpl implements Planner {

	public static final java.util.logging.Logger LOGGER = java.util.logging.Logger
			.getLogger(PlannerImpl.class.getName());
	
	private Lock plannerLock;
	private List<PlannedItem> plannedItems ;
	private Scheduler scheduler;
	private PlannedItem justPopped;
	
	public PlannerImpl(Scheduler scheduler) {
		super();
		this.plannerLock = new ReentrantLock();
		this.plannedItems = new ArrayList<PlannedItem>();
		this.scheduler = scheduler;
	}

	
	@Override
	public PlannedItem popNext() {
		PlannedItem retValue = null;
		try {
			Date curDate = new Date();
			this.plannerLock.lock();
			if (!this.plannedItems.isEmpty()) {
				for (PlannedItem pitm : this.plannedItems) {
					Date plannedDate = pitm.getPlannedDate();
					if (curDate.after(plannedDate)) {
						LOGGER.info("\t poped date "+curDate +">"+plannedDate);
						retValue = pitm;
					} else {
						LOGGER.info("\t still planned  "+curDate +"<"+plannedDate);
					}
				}
				if (retValue != null) {
					this.plannedItems.remove(retValue);
				}
			}
			justPopped = retValue;
			return retValue;
		} finally {
			this.plannerLock.unlock();
		}
	}

	
	@Override
	public PlannedItem plan(Station station, StopDownloadCondition condition, String title, Date plannedDate) {
		PlannedItem plannedItem = new PlannedItem(station, condition, UUID.randomUUID().toString(), title, plannedDate);
		this.plannedItems.add(plannedItem);
		if (!scheduler.isStarted()) {
			scheduler.start();
		}
		return plannedItem;
	}

	@Override
	public PlannedItem[] getPlannedItems() {
		return (PlannedItem[]) this.plannedItems.toArray(new PlannedItem[this.plannedItems.size()]);
	}


	@Override
	public Lock getPlannerLock() {
		return this.plannerLock;
	}


    @Override
    public void removePlannedItem(PlannedItem plannedItem) {
        try {
            this.plannerLock.lock();
            this.plannedItems.remove(plannedItem);
        } finally {
            this.plannerLock.unlock();
        }
    }


	@Override
	public PlannedItem getJustPopped() {
		return this.justPopped;
	}
}
